<template>
  <div class="app-container">
    <div style="margin-bottom:10px">
        <p>请选择统计方式：</p>
        <el-checkbox-group v-model="checkList">
            <el-checkbox label="按照加工企业统计"></el-checkbox>
            <el-checkbox label="按照产品名称统计"></el-checkbox>
            <el-checkbox label="按照产品号码统计"></el-checkbox>
        </el-checkbox-group>
    </div>
    <div class="filter-container" style="margin-bottom:10px">
        <p>请选择过滤条件：</p>
      <el-select v-model="listQuery.name" placeholder="品名" clearable style="width: 90px;margin-bottom:3px" class="filter-item" filterable>
        <el-option v-for="item in selectItems.goods" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="listQuery.number" placeholder="品号" clearable style="width: 90px;margin-bottom:3px" class="filter-item" :disabled="!listQuery.name" filterable>
        <el-option v-for="item in selectItems.goodsNumber[listQuery.name]" :key="item.code" :label="item.code" :value="item.code"/>
      </el-select>
      <el-select v-model="listQuery.company" placeholder="加工企业" clearable style="width: 90px;margin-bottom:3px" class="filter-item" filterable>
        <el-option v-for="item in selectItems.companies" :key="item" :label="item" :value="item"/>
      </el-select>
      <el-date-picker v-model="listQuery.datestart" type="date" placeholder="开始时间" />
      <el-date-picker v-model="listQuery.dateend" type="date" placeholder="截止时间" />
      <br/>
      <br/>

      <el-button v-waves class="filter-item" style="margin-bottom:3px" type="primary" icon="el-icon-search" size='mini' @click="handleFilter">
        搜索
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" style="margin-bottom:3px" type="primary" icon="el-icon-download" size='mini' @click="handleDownload">
        导出excel
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="产品名称" prop="name" align="center" width="100" v-if="showColFlag.name" :key="'name'">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      
      <el-table-column label="品号" min-width="100px" v-if="showColFlag.number" :key="'number'">
        <template slot-scope="{row}">
            {{ row.number }} 
        </template>
      </el-table-column>

      <el-table-column label="加工企业" min-width="100px" v-if="showColFlag.company" :key="'company'">
        <template slot-scope="{row}">
            {{ row.company }} 
        </template>
      </el-table-column>

      <el-table-column label="发出总匹数" min-width="100px">
        <template slot-scope="{row}">
            {{ row.outPiece | fixedFilter}} 
        </template>
      </el-table-column>

      <el-table-column label="发出总米数" min-width="100px">
        <template slot-scope="{row}">
            {{ row.outLength | fixedFilter}} 
        </template>
      </el-table-column>

      <el-table-column label="发入总匹数" min-width="100px">
        <template slot-scope="{row}">
            {{ row.inPiece | fixedFilter}} 
        </template>
      </el-table-column>

      <el-table-column label="发入总米数" min-width="100px">
        <template slot-scope="{row}">
            {{ row.inLength | fixedFilter}} 
        </template>
      </el-table-column>

      <el-table-column label="总结存匹数" min-width="100px">
        <template slot-scope="{row}">
            {{ row.leftPiece | fixedFilter}} 
        </template>
      </el-table-column>

      <el-table-column label="总缩率" min-width="100px">
        <template slot-scope="{row}">
            {{ row.rate | balanceFilter}} 
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

  </div>
</template>

<script>
import { fetchList, fetchSelectItemList} from '@/api/processStatistics'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'saleStatistis',
  components: { Pagination },
  directives: { waves },
  computed:{ user:{
    get(){
      const token = this.$store.getters.token;
      return{
        name:token.name,
        role:token.role
      }
    }
  }},
  filters: {
    balanceFilter(value) {
      if(isNaN(value)) return 0;
      return String((value * 100).toFixed(1)) + '%';
    },
    fixedFilter(value){
      if(isNaN(value)) return 0;
        return (value * 100).toFixed(1);
    },
    startTimeFilter(value){
        // console.log(value)
        if(value.datestart!=undefined){
            return value.datestart;
        }
        else{
            return "--"
        }
    }
  },
  data() {
    return {
      checkList:["按照加工企业统计"],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        // name:'',
        // number:'',
        // warehouse:'',
        // date:'',
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      selectItems:{goods:[],goodsNumber:{},companies:[]},
      showReviewer: false,
      temp: {
        number: '',
        name: '',
        customer:'',
        outPiece:'',
        outLength:'',
        inPiece:0,
        inLength:0,
        leftPiece:'',
        rate:0,
        date:'',
        operator:'',
        remark:'',
      },
      dialogFormVisible: false,
      dialogStatus: '',
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '必须选择品名', trigger: 'change' }],
        number: [{ required: true, message: '必须选择品号', trigger: 'change' }],
        warehouse: [{ required: true, message: '必须选择仓库', trigger: 'change' }],
        customer: [{ required: true, message: '必须选择客户', trigger: 'change' }],
        date: [{ required: true, message: '日期必须填写', trigger: 'change' }],
        piece: [{ required: true, message: '必须填写数量', trigger: 'blur' }],
        length: [{ required: true, message: '必须填写米数', trigger: 'blur' }],
      },
      downloadLoading: false,
      showColFlag:{company: false, name: false, number: false}
    }
  },
  created() {
    this.getItemList();
  },
  methods: {
    getList() {
    if(this.checkList.length == 0){
        alert("请至少选择一种统计方式！");
        return;
    }
      this.listLoading = true;
      for(let i in this.listQuery){
        if(this.listQuery[i] == null){
          delete this.listQuery[i];
        }
      }
      let param = {query: this.listQuery, method:{checkList:this.checkList}}
      fetchList(param).then(response => {
        this.list = response.list.map(v=>{
            for(let i in v._id){
                v[i] = v._id[i];
            }
            if(this.listQuery.datestart != undefined){
                v.datestart = this.listQuery.datestart;
            }
            else{
                v.datestart = '--';
            }
            if(this.listQuery.dateend != undefined){
                v.dateend = this.listQuery.dateend;
            }
            else{
                v.dateend = '--';
            }
            return v;
        });
        if(this.list.length > 0){
          if(this.list[0].company != undefined){
            this.showColFlag.company = true;
          }
          else{
            this.showColFlag.company = false;
          }
          if(this.list[0].name != undefined){
            this.showColFlag.name = true;
          }
          else{
            this.showColFlag.name = false;
          }
          if(this.list[0].number != undefined){
            this.showColFlag.number = true;
          }
          else{
            this.showColFlag.number = false;
          }
        }
        this.total = response.total;
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 500)
      })
    },
    getItemList(){
      fetchSelectItemList().then(response => {
        this.selectItems.goods = response.goods;
        this.selectItems.goodsNumber = response.goodsNumber;
        this.selectItems.companies = response.companies;
        this.getList();
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'date') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = +1
      } else {
        this.listQuery.sort = -1
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp= {
        number: '',
        name: '',
        customer:'',
        outPiece:'',
        outLength:'',
        inPiece:0,
        inLength:0,
        leftPiece:'',
        rate:0,
        date:'',
        operator:'',
        remark:'',
      }
    },
   
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['发出总匹数', '发出总米数', '发入总匹数', '发入总米数','总缩率','起始时间', '终止时间'];
        const filterVal = [ 'outPiece', 'outLength','inPiece', 'inLength', 'balance', 'datestart', 'dateend'];
        if(this.list[0].company!=undefined){
            tHeader.unshift('加工企业');
            filterVal.unshift('company');
        }
        if(this.list[0].name!=undefined){
            tHeader.unshift('品名');
            filterVal.unshift('name');
        }
        if(this.list[0].number!=undefined){
            tHeader.unshift('品号');
            filterVal.unshift('number');
        }
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '加工统计'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          // return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
